package com.cn.mmd.controller;

import com.cn.mmd.model.*;
import com.cn.mmd.service.*;
import com.cn.mmd.tools.GetLimitNum;
import net.sf.json.JSONArray;
import com.sun.tools.internal.ws.processor.model.Model;


import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.ref.SoftReference;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 *问卷控制类
 * Created by Administrator on 2016/6/29.
 */
@Controller
@RequestMapping(value ="Questionnaire")

public class QuestionnaireController {

    @Autowired
    QuestionnaireService questionnaireService;
    @Autowired
    EvaluateTeacherService evaluateTeacherService;
    @Autowired
    LogController logController;
    @Autowired
    StudentService studentService;
    @Autowired
    EmploymentService employmentService;
    @Autowired
    CourseService courseService;
    @Autowired
    TeacherService teacherService;
    @Autowired
    TokenController tokenController;
    @Autowired
    StudentCountService studentCountService;
    @Autowired
    StudentCountController studentCountController;



    /**
     * 教师端发布问卷
     * @param request
     * @return
     * @throws com.alibaba.fastjson.JSONException
     */
    @RequestMapping(value = "teacherInsertQuestionnaire")
    public synchronized @ResponseBody Map<String,Object> teacherInsertQuestionnaire(HttpServletRequest request)throws Exception {

        Map<String, Object> map = new HashMap<String, Object>();

        //接收前台传来的json对象
        String questionnaire = request.getParameter("questionnaire");
        System.out.println("接收的对象："+questionnaire);
        if (questionnaire.equals("")||questionnaire==null){
            map.put("code", 206);
            map.put("message", "问卷对象为空");
//            map.put("data", "");
        }
        String teacherId=request.getParameter("teacherId");
        String token=request.getParameter("token");

        TeacherData teacherData;
        teacherData = (TeacherData) tokenController.token(teacherId, token);
        if (teacherData==null){
            map.put("code", 205);
            map.put("message", "您暂无权限做此操作");
//            map.put("data", "");
            return map;
        }

        //System.out.print(questionnaire);
        //转为json格式

        JSONObject jsonObject =JSONObject.fromObject(questionnaire);

        System.out.println("解析出来的数据2："+jsonObject);

        String publisherId = jsonObject.getString("publisherId");//发布方id
        String releaseToWho = jsonObject.getString("releaseToWho");//问卷具体面向的对象，如具体的班级、课程等
        System.out.println("具体发布的对象："+releaseToWho);
        String publishObjects = jsonObject.getString("publishObjects");//问卷面向群体  教师端默认为“班级”
        String questionnaireTitle = jsonObject.getString("questionnaireTitle");//问卷标题
        String questionnaireExplain = jsonObject.getString("questionnaireExplain");//问卷说明  教师端默认为“教师发布”
        String questionnaireResults = jsonObject.getString("questionnaireResult");//问卷问题数组
        JSONArray jsonArray = JSONArray.fromObject(questionnaireResults);//解析问卷问题数组

        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//可以方便地修改日期格式
        String nowTime = dateFormat.format(now);//时间

        //System.out.println(publisherId+"---"+publishObjects+"---"+questionnaireTitle+"---"+nowTime);
        Questionnaire questionnaire1 = new Questionnaire(publisherId, publishObjects, questionnaireTitle, nowTime, questionnaireExplain, releaseToWho);

        int a = questionnaireService.insertQuestionnaire(questionnaire1);//添加问卷


        if (a > 0) {//添加成功
            Questionnaire questionnaire2 = questionnaireService.selectPrimaryKey(publisherId, publishObjects, questionnaireTitle, nowTime);//查出当前问卷的id

            int questionnaireId = questionnaire2.getQuestionnaireid();//问卷id

            int number = 0;

                String[] releaseToWho1 = questionnaire2.getReleasetowho().split(",");//班级可能有多个，用逗号分割

                List<Integer> cList = new ArrayList<Integer>();
                for (int i = 0; i < releaseToWho1.length; i++) {
                    //System.out.println("releaseToWho1[i]: " + releaseToWho1[i]);
                    int num = questionnaireService.selectNumber(releaseToWho1[i]);
                    //System.out.println("num:"+num);
                    number += num;//统计人数
                   // System.out.println("number:"+number);
                    List studentIdList = questionnaireService.selectByStudentClass(releaseToWho1[i]);
                   // System.out.print("studentIdList: " + studentIdList.size());
                    if (studentIdList.size() > 0) {
                        for (int n = 0; n < studentIdList.size(); n++) {

                            //System.out.print("   studentId" + studentIdList.get(n));
                            String state = "NO";//设置状态为未填写

                            QuestionnaireStudent questionnaireStudent = new QuestionnaireStudent((String) studentIdList.get(n), questionnaireId, state, nowTime);

                            int c = studentService.insertStuQues(questionnaireStudent);
                            cList.add(c);
                        }
                    } else {
                        //System.out.println("未查到相关学生");
                    }
                }
                //System.out.print("number:" + number + "---cList:" + cList.size());
                if (cList.size() != number) {

//                    int x=questionnaireService.delQuestionnaire(questionnaireId);
//                    int y=studentService.delStuQues(questionnaireId);

                    map.put("code", 204);
                    map.put("message", "问卷关联学生失败");
//                    map.put("data", "");

                    return map;
                }

            QuestionnaireStatistical questionnaireStatistical=new QuestionnaireStatistical();

            questionnaireStatistical.setQuestionnaireid(questionnaireId);
            questionnaireStatistical.setPublishobjects(releaseToWho);
            questionnaireStatistical.setNumber(number);
            questionnaireStatistical.setNotchoosenumber(number);
            questionnaireStatistical.setChoosenumber(0);
            int c=questionnaireService.insertStatistical(questionnaireStatistical);
            if (c>0){
                //System.out.println("统计人数成功");
            }else{
//                int x=questionnaireService.delQuestionnaire(questionnaireId);
//                int y=studentService.delStuQues(questionnaireId);

                map.put("code",201);
                map.put("message","人数统计失败");
//                map.put("data", "");
                return map;
            }


            int j=0;
            int i=0;
            List list=new ArrayList();
            for(;i<jsonArray.size(); i++){
                JSONObject jsonJ = jsonArray.getJSONObject(i);

                int questionNumber= jsonJ.getInt("questionNumber");//问题序号
                String questionContent= jsonJ.getString("questionContent");//问题内容
                String options=jsonJ.getString("options");//选项  存123，用!分割;
                String optionsDescribe=jsonJ.getString("optionsDescribe");//选项描述

                String problemTypes=jsonJ.getString("problemTypes");//问题类型，教师端默认为“选择题”
                String couplingIndex=jsonJ.getString("couplingIndex");//问题关联的标签，教师端默认没有关联标签，默认为""

                QuestionnaireResult questionnaireResult=new QuestionnaireResult();

                questionnaireResult.setQuestionnaireid(questionnaireId);
                questionnaireResult.setQuestionnumber(questionNumber);
                questionnaireResult.setQuestioncontent(questionContent);
                questionnaireResult.setOptions(options);
                questionnaireResult.setOptionsdescribe(optionsDescribe);
                questionnaireResult.setProblemtypes(problemTypes);
                questionnaireResult.setCouplingindex(couplingIndex);

                int b = questionnaireService.addQuestion(questionnaireResult);//添加问题
                if (b>0){
                    j++;
                }else {
                    int x=questionnaireService.delQuestionnaire(questionnaireId);

                    map.put("code",202);
                    map.put("message","设置问题失败");
//                    map.put("data", "");
                    return map;
                }

                if(couplingIndex!=null || couplingIndex!=""){
                    list.add(couplingIndex);
                }

            }

            if (j==i){

                //老师日志
                   //添加日志！！
                   //操作内容
                String logContent="发布问卷“"+questionnaireTitle+"”成功";
                //System.out.println(logContent);
                logController.logTeacher(logContent, publisherId);

                map.put("code",200);
                map.put("message","设置问卷成功");
//                map.put("data", 1);
            }else{
                map.put("code",202);
                map.put("message","设置问题失败");
//                map.put("data", "");
                return map;
            }

        }else{
            map.put("code",203);
            map.put("message","设置问卷失败");
//            map.put("data","");
            return map;
        }

    return map;
    }




    /**
     * 后台发布问卷
     * @param request
     * @return
     * @throws com.alibaba.fastjson.JSONException
     */
    @RequestMapping(value = "insertQuestionnaire")
    public synchronized @ResponseBody Map<String,Object> insertQuestionnaire(HttpServletRequest request)throws Exception {

        Map<String,Object> map = new HashMap<String,Object>();

        //接收前台传来的json字符串
        String questionnaire =request.getParameter("questionnaire");

        //System.out.print(questionnaire);
        //转为json格式
        JSONObject jsonObject=JSONObject.fromObject(questionnaire);
        String publisherId = jsonObject.getString("publisherId");//发布方id
        String releaseToWho=jsonObject.getString("releaseToWho");//问卷具体面向的对象，如具体的班级、课程等
        String publishObjects = jsonObject.getString("publishObjects");//问卷面向群体，如班级、课程、老师等
        String questionnaireTitle = jsonObject.getString("questionnaireTitle");//问卷标题
        String questionnaireExplain=jsonObject.getString("questionnaireExplain");//问卷说明  该问卷的作用标记，暂时有教评、SCL-90、就业、其他和教师发布（教师发布为教师端发布）
        String questionnaireResults=jsonObject.getString("questionnaireResult");//问卷问题数组
        JSONArray jsonArray=JSONArray.fromObject(questionnaireResults);//解析问卷问题数组

        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//可以方便地修改日期格式
        String nowTime = dateFormat.format( now );//时间

        //System.out.println(publisherId+"---"+publishObjects+"---"+questionnaireTitle+"---"+nowTime);

        if (publishObjects==null||publishObjects.equals("")||releaseToWho==null||releaseToWho.equals("")
                ||questionnaireTitle==null||questionnaireTitle.equals("")||questionnaireExplain==null||questionnaireExplain.equals("")){
            map.put("code",205);
            map.put("message","请填写完整");
//            map.put("data", "");
            return map;
        }

        Questionnaire questionnaire1=new Questionnaire(publisherId,publishObjects,questionnaireTitle,nowTime,questionnaireExplain,releaseToWho);

        int a=questionnaireService.insertQuestionnaire(questionnaire1);//添加问卷

        if (a>0){//添加成功
            Questionnaire questionnaire2=questionnaireService.selectPrimaryKey(publisherId,publishObjects,questionnaireTitle,nowTime);//查出当前问卷的id

            int questionnaireId=questionnaire2.getQuestionnaireid();//问卷id

            int number=0;
            if (questionnaire2.getPublishobjects().equals("班级")){//如果选择面向的群体为班级

                String[] releaseToWho1=questionnaire2.getReleasetowho().split(",");//班级可能有多个，用逗号分割

                List cList=new ArrayList();
                for (int i=0;i<releaseToWho1.length;i++){
                   // System.out.println("releaseToWho1[i]: "+releaseToWho1[i]);
                    int num=questionnaireService.selectNumber(releaseToWho1[i]);
                    number+=num;//统计人数
                    List studentIdList=questionnaireService.selectByStudentClass(releaseToWho1[i]);
                   // System.out.print("studentIdList: "+studentIdList.size());
                    if (studentIdList.size()>0){
                        for (int n=0;n<studentIdList.size();n++){

                           // System.out.print("   studentId"+studentIdList.get(n));
                            String state="NO";//设置状态为未填写

                            QuestionnaireStudent questionnaireStudent=new QuestionnaireStudent((String)studentIdList.get(n),questionnaireId,state,nowTime);

                            int c=studentService.insertStuQues(questionnaireStudent);
                            cList.add(c);
                        }
                    }else {
                        //System.out.println("未查到相关学生");
                    }
                }
                //System.out.print("number:"+number+"---cList:"+cList.size());
                if (cList.size()!=number){
                    map.put("code",204);
                    map.put("message","问卷关联学生失败");
//                    map.put("data", "");
                    return map;
                }


            }else  if (questionnaire2.getPublishobjects().equals("课程")){//如果选择面向的群体为课程

                Course course=questionnaireService.selectClasses(releaseToWho);//如果是课程，只能选择一门课程

                String[] stuCla=course.getCourseclasss().split(",");//课程教学组下有多个班级，用逗号分割

                List cList=new ArrayList();
                for (int i=0;i<stuCla.length;i++){
                    int num=questionnaireService.selectNumber(stuCla[i]);
                    number+=num;//统计人数
                    List studentIdList=questionnaireService.selectByStudentClass(stuCla[i]);
                    if (studentIdList.size()>0){
                        for (int n=0;n<studentIdList.size();n++){

                            String state="NO";//设置状态为未填写

                            QuestionnaireStudent questionnaireStudent=new QuestionnaireStudent((String)studentIdList.get(n),questionnaireId,state,nowTime);

                            int c=studentService.insertStuQues(questionnaireStudent);
                            cList.add(c);
                        }
                    }
                }

            }else if (questionnaire2.getPublishobjects().equals("年级")){
                //如果是年级  则问卷面向的是年级的学生  如2015级
                List<Student> studentList=studentService.selectByClasss(releaseToWho);
                if (studentList.size()>0){
                    String state="NO";//设置状态为未填写
                    for (Student s:studentList){
                        QuestionnaireStudent questionnaireStudent=new QuestionnaireStudent(s.getStudentid(),questionnaireId,state,nowTime);
                        studentService.insertStuQues(questionnaireStudent);
                    }
                    number=studentList.size();
                }

            }else {
                //问卷暂时只可面向班级、课程和学校，可添加其他群体
            }

           // System.out.println("总人数："+number);

            QuestionnaireStatistical questionnaireStatistical=new QuestionnaireStatistical();

            questionnaireStatistical.setQuestionnaireid(questionnaireId);
            questionnaireStatistical.setPublishobjects(releaseToWho);
            questionnaireStatistical.setNumber(number);
            questionnaireStatistical.setNotchoosenumber(number);
            questionnaireStatistical.setChoosenumber(0);
            int c=questionnaireService.insertStatistical(questionnaireStatistical);
            if (c>0){
                //System.out.println("统计人数成功");
            }else{
                map.put("code",201);
                map.put("message","人数统计失败");
//                map.put("data", "");
                return map;
            }


            int j=0;
            int i=0;
            List list=new ArrayList();

            for(;i<jsonArray.size(); i++){
                JSONObject jsonJ = jsonArray.getJSONObject(i);

                int questionNumber=jsonJ.getInt("questionNumber");//问题序号
                String questionContent= jsonJ.getString("questionContent");//问题内容
                String questionState=jsonJ.getString("questionState");//问题头
                String questionDescribe=jsonJ.getString("questionDescribe");//问题描述
                String options=jsonJ.getString("options");//问题选项
                String optionsDescribe=jsonJ.getString("optionsDescribe");//选项描述
                String problemTypes=jsonJ.getString("problemTypes");//问题类型
                //问题关联的三级指标名，选择题格式为：标签库名！三级指标。打分题格式为：选项！标签库名！三级指标1！！选项！标签库名！三级指标2！！...
                //打分题与选择题格式不同，需前端判断拼接！！！！
                //每个指标由标签库名和三级指标构成，用单感叹号拼接；打分题可能有多个关联的指标，用双感叹号拼接
                String couplingIndex=jsonJ.getString("couplingIndex");
                System.out.println("关联标签："+couplingIndex);

                JSONArray optionJson=JSONArray.fromObject(options);
                JSONArray optionsDescribeJson=JSONArray.fromObject(optionsDescribe);
                JSONArray couplingIndexJson=null;
                JSONArray scoreJson=null;

                String op="",opDes="",coupInd="";

                if (problemTypes.equals("选择题")){
                    coupInd=couplingIndex;
                    String score=jsonJ.getString("score");
                    scoreJson=JSONArray.fromObject(score);
                    System.out.println("这是道选择题");
                    for (int x=0;x<optionJson.size();x++){

                        if (opDes.equals("")){
                            opDes=optionsDescribeJson.get(x).toString();
                        }else {
                            opDes=opDes+"!!"+optionsDescribeJson.get(x).toString();
                        }
//                        int score1=Integer.parseInt(scoreJson.get(x).toString().split("!!")[0]);
                        if (Integer.parseInt(scoreJson.get(x).toString())==0){
                            System.out.println("这题没分数");
                            if (op.equals("")){
                                op=""+optionJson.get(x).toString();
                            }else {
                                op=op+"!!"+optionJson.get(x).toString();
                            }
                        }else {
                            if (op.equals("")){
                                op=scoreJson.get(x).toString();
                            }else {
                                op=op+"!!"+scoreJson.get(x).toString();
                            }
                        }

                    }

                }else if (problemTypes.equals("打分题")){
                    couplingIndexJson=JSONArray.fromObject(couplingIndex);

                    for (int x=0;x<optionJson.size();x++){
                        if (op.equals("")){
                            op=optionJson.get(x).toString();
                        }else {
                            op=op+"!!"+optionJson.get(x).toString();
                        }
                        if (opDes.equals("")){
                            opDes=optionsDescribeJson.get(x).toString();
                        }else {
                            opDes=opDes+"!!"+optionsDescribeJson.get(x).toString();
                        }
                        if (couplingIndexJson.get(x).toString()==null||couplingIndexJson.get(x).toString().equals("")){

                            System.out.println("此问卷无标签");
                        }else {
                            if (coupInd.equals("")){
                                coupInd=couplingIndexJson.get(x).toString();
                            }else {
                                coupInd=coupInd+"!!"+couplingIndexJson.get(x).toString();
                            }
                        }
                    }
                }

                QuestionnaireResult questionnaireResult=new QuestionnaireResult();

                questionnaireResult.setQuestionnaireid(questionnaireId);
                questionnaireResult.setQuestionnumber(questionNumber);
                questionnaireResult.setQuestioncontent(questionContent);
                questionnaireResult.setQuestionstate(questionState);
                questionnaireResult.setQuestiondescribe(questionDescribe);
                questionnaireResult.setOptions(op);
                questionnaireResult.setOptionsdescribe(opDes);
                questionnaireResult.setCouplingindex(coupInd);
                questionnaireResult.setProblemtypes(problemTypes);

                int b = questionnaireService.addQuestion(questionnaireResult);//添加问题
                if (b>0){
                    j++;
                }else {
                    map.put("code",202);
                    map.put("message","设置问题失败");
//                    map.put("data", "");

                    return map;
                }
            }

            if (j==i){

                if (list.size()>0){//后台日志

                    //添加日志！！
                    //操作内容
                    String logContent="发布问卷“"+questionnaireTitle+"”成功";
                    //System.out.println(logContent);
                    logController.logManage(logContent, publisherId);
                }else {//老师日志
                    //添加日志！！
                    //操作内容
                    String logContent="发布问卷“"+questionnaireTitle+"”成功";
                    //System.out.println(logContent);
                    logController.logTeacher(logContent, publisherId);
                }

                map.put("code",200);
                map.put("message","设置问卷成功");
//                map.put("data", "");
            }else{
                map.put("code",202);
                map.put("message","设置问题失败");
//                map.put("data", "");
                return map;
            }

        }else{
            map.put("code",203);
            map.put("message","设置问卷失败");
//            map.put("data","");
            return map;
        }

        return map;
    }

    /**
     * 学生查看关联自己的问卷（需要填写的问卷）
     * @param request
     * @return
     */
    @RequestMapping(value = "selectStuQues")
    public synchronized @ResponseBody Map<String,Object> selectStuQues(HttpServletRequest request){
        Map<String,Object> map = new HashMap<String,Object>();
        Map<String,Object> map2 = new HashMap<String,Object>();
        List<Map<String,Object>> mapList=new ArrayList<Map<String, Object>>();
        GetLimitNum G=new GetLimitNum();

        String studentId=request.getParameter("studentId");//传入学生id
        String state="NO";
        int startrow=Integer.parseInt(request.getParameter("startrow"));//查第几页 >=1
        int pageSize=Integer.parseInt(request.getParameter("pageSize"));//一页多少条数据

        String token=request.getParameter("token");

        StudentApp studentApp;
        studentApp = (StudentApp) tokenController.token1(studentId, token);
        if (studentApp==null){
            map.put("code", 202);
            map.put("message", "您暂无权限做此操作");
//            map.put("data", "");
            return map;
        }

        QuestionnaireStudent questionnaireStudent=new QuestionnaireStudent();
        questionnaireStudent.setStudentid(studentId);
        questionnaireStudent.setState(state);

        int num=studentService.selectCountStuQues(questionnaireStudent);
        if (num>0){
            num=G.getLimitNum(num, pageSize);
            int page=(startrow-1)*pageSize;//从哪一条开始
            QuestionnaireStudent questionnaireStudent1=new QuestionnaireStudent(studentId,state,page,pageSize);

            //List<LabelPackage> packageList=labelService.selectAllPackage(labelPackage);


            List<QuestionnaireStudent> list=studentService.selectStuQues(questionnaireStudent1);


            for (int i=0;i<list.size();i++){

                Questionnaire questionnaire=questionnaireService.selectByQuestionnaireId(list.get(i).getQuestionnaireid());
                if (questionnaire!=null){
                    Map<String,Object> map1 = new HashMap<String,Object>();
                    int questionnaireId=questionnaire.getQuestionnaireid();//问卷id
                    String questionnaireTitle=questionnaire.getQuestionnairetitle();//问卷名
                    String publisher=questionnaire.getPublisherid();//发布方
                    String questionnaireExplain=questionnaire.getQuestionnaireexplain();//问卷说明

                    Teacher teacher=teacherService.serlectTeacher(publisher);
                    if (teacher==null||teacher.getTeachername()==null){
                        //发布人查询失败
                        map1.put("publisher",publisher);
                    }else {
                        map1.put("publisher",teacher.getTeachername());
                    }

                    if (questionnaireExplain.equals("就业质量")){
                        EmploymentQuestionnaire employmentQuestionnaire=employmentService.selectEmploymentQuestionnaire(questionnaireId);
                        if (employmentQuestionnaire!=null){
                            map1.put("questionnaireURL",employmentQuestionnaire.getQuestionnaireurl());//问卷链接
                            String releaseTime=questionnaire.getReleasetime();

                            map1.put("questionnaireId",questionnaireId);
                            map1.put("questionnaireTitle",questionnaireTitle);
                            map1.put("questionnaireExplain",questionnaireExplain);

                            map1.put("releaseTime",releaseTime);
                            mapList.add(map1);
                        }
//                        else {
//                            map.put("code",202);
//                            map.put("message","就业问卷URL提取失败");
//                            map.put("data","");
//                            return map;
//                        }

                    }else {
                        map1.put("questionnaireURL","");

                        String releaseTime=questionnaire.getReleasetime();
                        map1.put("questionnaireId",questionnaireId);
                        map1.put("questionnaireTitle",questionnaireTitle);
                        map1.put("questionnaireExplain",questionnaireExplain);

                        map1.put("releaseTime",releaseTime);
                        mapList.add(map1);

                    }

                }

            }

            map2.put("pages",num);
            map2.put("questionnaireList",mapList);

            map.put("code",200);
            map.put("message","查询关联表成功");
            map.put("data",map2);
        }else {
            map.put("code",201);
            map.put("message","暂无需要您填写的问卷");
//            map.put("data","");
        }

        return map;
    }

    /**
     * 查看问卷详情    这里有对问卷类型的判断！！
     * @param request
     * @return
     */
    @RequestMapping(value = "selectQuestionnaireParticulars")
    public synchronized @ResponseBody Map<String,Object> selectQuestionnaireParticulars(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<String, Object>();
        List<Map<String,Object>> mapList=new ArrayList<Map<String, Object>>();
        Map<String,Object> map0 = new HashMap<String,Object>();
        int questionnaireId=Integer.parseInt(request.getParameter("questionnaireId"));//问卷id

        String operatorId=request.getParameter("operatorId");//操作人id
        String operatorType=request.getParameter("operatorType");//操作人类型
        String token=request.getParameter("token");

        if (operatorType.equals("教师")){

            TeacherData teacherData;
            teacherData = (TeacherData) tokenController.token(operatorId, token);
            if (teacherData==null){
                map.put("code", 202);
                map.put("message", "您暂无权限做此操作");
//                map.put("data", "");
                return map;
            }

        }else if (operatorType.equals("学生")){
            StudentApp studentApp;
            studentApp = (StudentApp) tokenController.token1(operatorId, token);
            if (studentApp==null){
                map.put("code", 202);
                map.put("message", "您暂无权限做此操作");
//                map.put("data", "");
                return map;
            }
        }


        Questionnaire questionnaire=questionnaireService.selectByQuestionnaireId(questionnaireId);
        String questionnaireExplain=null;
        if (questionnaire!=null){

            String questionnaireTitle=questionnaire.getQuestionnairetitle();//问卷名
            questionnaireExplain=questionnaire.getQuestionnaireexplain();//问卷说明
            String publisher=questionnaire.getPublisherid();//发布方
            String releaseTime=questionnaire.getReleasetime();

            Teacher teacher=teacherService.serlectTeacher(publisher);
            if (teacher==null||teacher.getTeachername()==null){
                //发布人查询失败
                map0.put("publisher", publisher);
            }else {
                map0.put("publisher", teacher.getTeachername());
            }

            if (questionnaireExplain.equals("教师发布")){
                map0.put("questionnaireType",0);
            }else if (questionnaireExplain.equals("就业质量")){
                map0.put("questionnaireType",1);
            }else if (questionnaireExplain.equals("SCL-90")){
                map0.put("questionnaireType",2);
            }else if (questionnaireExplain.equals("课程评价")){//教评
                map0.put("questionnaireType",3);
            }else {//其他类型的问卷
                map0.put("questionnaireType",4);
            }

            map0.put("questionnaireTitle",questionnaireTitle);
            map0.put("questionnaireExplain",questionnaireExplain);
            map0.put("releaseTime",releaseTime);
        }

        if (questionnaireExplain.equals("就业质量")){//就业问卷  连接到问卷星

            //直接跳转
//            EmploymentQuestionnaire employmentQuestionnaire=employmentService.selectEmploymentQuestionnaire(questionnaireId);
//            if (employmentQuestionnaire!=null){
//                map0.put("questionnaireURL",employmentQuestionnaire.getQuestionnaireurl());
//                map.put("code",200);
//                map.put("message","问题查询成功");
//                map.put("data",map0);
//            }else {
//                map.put("code",202);
//                map.put("message","就业问卷URL提取失败");
//                map.put("data","");
//                return map;
//            }


        }else {
            List<QuestionnaireResult> questionnaireResults=questionnaireService.selectQuestionnaireResult(questionnaireId);

            if (questionnaireResults.size()>0){

                for (int i=0;i<questionnaireResults.size();i++){
                    Map<String, Object> map1 = new HashMap<String, Object>();
                    List<Map<String,Object>> mapList1=new ArrayList<Map<String, Object>>();
                    int questionId=questionnaireResults.get(i).getQuestionid();//问题id
                    int questionNumber=questionnaireResults.get(i).getQuestionnumber();//序号
                    String questioncontent= questionnaireResults.get(i).getQuestioncontent();//问题内容（题目）
                    String optionss=questionnaireResults.get(i).getOptions();//选项
                    String optionsDescribess=questionnaireResults.get(i).getOptionsdescribe();//选项描述
                    String questionTypes=questionnaireResults.get(i).getProblemtypes();//问题类型
                    String [] options=optionss.split("!!");
                    String [] optionsDescribes=optionsDescribess.split("!!");

                    for (int a=0;a<options.length;a++){
                        Map<String, Object> map2 = new HashMap<String, Object>();
                        String option=options[a];
                        String optionsDescribe=optionsDescribes[a];
                        map2.put("option",option);   //添加选项、选项描述到每道题中  arrayList格式！
                        map2.put("optionsDescribe",optionsDescribe);
                        mapList1.add(map2);
                    }

                    //System.out.println("选项list："+mapList1);
                    map1.put("questionId", questionId);
                    map1.put("questionNumber", questionNumber);
                    map1.put("questioncontent",questioncontent);
                    map1.put("questionTypes",questionTypes);
                    map1.put("options",mapList1);

                    mapList.add(map1);
                }
                map0.put("question",mapList);

                map.put("code",200);
                map.put("message","问题查询成功");
                map.put("data",map0);

            }else {
                map.put("code",201);
                map.put("message","问题查询失败");
//                map.put("data","");
            }
        }

        return map;
    }


    /**
     * 查看我发布的问卷详情统计   只适用于app教师端的查看详情  不适用后台 没有打分题
     * @param request
     * @return
     */
    @RequestMapping(value = "selectQuestionnaireStatistics")
    public synchronized @ResponseBody Map<String,Object> selectQuestionnaireStatistics(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<String, Object>();

        int questionnaireId=Integer.parseInt(request.getParameter("questionnaireId"));//问卷id
//        System.out.println("接收到的id："+questionnaireId);

        String teacherId=request.getParameter("teacherId");
//        System.out.println(teacherId);
        String token=request.getParameter("token");

        TeacherData teacherData;
        teacherData = (TeacherData) tokenController.token(teacherId, token);
        if (teacherData==null){
            map.put("code", 203);
            map.put("message", "您暂无权限做此操作");
//            map.put("data", "");
            return map;
        }


        QuestionnaireStatistical questionnaireStatistical=questionnaireService.selectStatistical(questionnaireId);
        List<QuestionnaireResult> questionnaireResults=questionnaireService.selectQuestionnaireResult(questionnaireId);

        if (questionnaireStatistical!=null&&questionnaireResults!=null){

            String statistical=questionnaireStatistical.getDetailedstatistical();//统计结果

//            System.out.println("统计结果："+statistical);
            if (statistical!=null) {
                String[] statisticals = statistical.split("!!");

//                System.out.println("有多少选项：" + statisticals.length);
//                List<Map> list = new ArrayList<Map>();
                List<Map> list1=new ArrayList<Map>();
//                Map map1 = null;
//                for (int h = 0; h < questionnaireResults.size(); h++) {
//                map1=new HashMap();
                for (int i=0;i<statisticals.length;i++){

                    String [] optStist=statisticals[i].split("!");

                    if (optStist.length==2){//选择题

                        Map<Integer,String> map2=new HashMap<Integer,String>();
                        int questionNum=Integer.parseInt(optStist[0]);
                        String opStist1=optStist[1];
                        map2.put(questionNum,opStist1);
                        list1.add(map2);
                    }
                }
//                System.out.println(list1);

                Map<Object, List> map3 = new HashMap<Object, List>();
                for (Map m : list1) {
                    Iterator it = m.keySet().iterator();
                    while (it.hasNext()) {
                        Object key = it.next();
                        if (!map3.containsKey(key)) {
                            List<Object> newList = new ArrayList<Object>();
                            newList.add(m.get(key));
                            map3.put(key, newList);
                        } else {
                            map3.get(key).add(m.get(key));
                        }
                    }
                }
//                System.out.println("map3:"+map3);
                List<Map> list2=null;
                List<Map> mapList=new ArrayList<Map>();
                for (Object key:map3.keySet()){
                    List value=map3.get(key);
                    String option="";
                    int stisNum=0;
                    list2 = new ArrayList<Map>();
                    for (int x=0;x<questionnaireResults.size();x++){
                        Map<String,Object> map4=new HashMap<String,Object>();
                        if (key==questionnaireResults.get(x).getQuestionnumber()){
//                            System.out.println("进入匹配："+key);
                            String questionContent=questionnaireResults.get(x).getQuestioncontent();

                            String[] ops = questionnaireResults.get(x).getOptions().split("!!");
                            String[] optionsDescribes = questionnaireResults.get(x).getOptionsdescribe().split("!!");
                            Map<String,Object> map5=null;
                            String str2="";
                            List<Object> list3=new ArrayList<Object>();
                            for (int y = 0; y < ops.length; y++) {

                                for (int a=0;a<value.size();a++) {

                                    option = value.get(a).toString().split("_")[0];
                                    list3.add(option);
                                    stisNum = Integer.parseInt(value.get(a).toString().split("_")[1]);
    //                                System.out.println("option："+option+"   "+stisNum);
//                                    System.out.println("进入for:" + option+"======="+ops[y]);

                                    map5=new HashMap<String,Object>();
                                    if (option.equals(ops[y]) ) {
//                                        System.out.println("进入if");
                                        String optionsDescrib = optionsDescribes[y];
//                                        System.out.println(key + "-----" + optionsDescribe);
                                        map5.put("option", option);
                                        map5.put("optionsDescribe", optionsDescrib);
                                        map5.put("stisNum",stisNum);

                                        list2.add(map5);
                                    }
                                }
                            }
                            String optionsDescribe="";
                            Map<String,Object> map6=null;

                            for(int y=0;y<ops.length;y++){
                                map6=new HashMap<String,Object>();
                                Boolean exists = (list3).contains(ops[y]);
                                if (exists) {

                                }else {
                                    str2 = ops[y];
                                    optionsDescribe = optionsDescribes[y];
//                                    System.out.println("没答的选项的描述："+optionsDescribe);
//                                    System.out.println(key + "-----" + optionsDescribe);
                                    if (str2!=""&&str2!=null){
                                        map6.put("option", str2);
                                        map6.put("optionsDescribe", optionsDescribe);
                                        map6.put("stisNum",0);
                                        list2.add(map6);
                                    }
                                }
                            }

//                            System.out.println("list2："+list2);
                            map4.put("questionNum", key);
                            map4.put("questionContent",questionContent);
                            map4.put("statistical",list2);
                            mapList.add(map4);
                        }
                    }
                }

//            }
                map.put("code",200);
                map.put("message","查询成功");
                map.put("data",mapList);
            }else {
                map.put("code",201);
                map.put("message", "该问卷暂时没有人填写");
//                map.put("data","");
            }


        }else {
            map.put("code",202);
            map.put("message","获取题目失败");
//            map.put("data","");
        }

        return map;
    }


    /**
     * 查看我发布的所有问卷
     * @param request
     * @return
     */
    @RequestMapping(value = "selectQuestionnaire")
    public synchronized @ResponseBody Map<String,Object> selectQuestionnaire(HttpServletRequest request){
        Map<String,Object> map0 = new HashMap<String,Object>();
        Map<String,Object> map1 = new HashMap<String,Object>();
        List<Map<String,Object>> mapList=new ArrayList<Map<String, Object>>();

        String publisherId=request.getParameter("teacherId");//前端传入教师工号
        int startrow=Integer.parseInt(request.getParameter("startrow"));//前端传入要查看第几页
        int pageSize=Integer.parseInt(request.getParameter("pageSize"));//前端传入一页有多少条数据
        String token=request.getParameter("token");

        TeacherData teacherData;
        teacherData = (TeacherData) tokenController.token(publisherId, token);
        if (teacherData==null){
            map0.put("code", 201);
            map0.put("message", "您暂无权限做此操作");
//            map0.put("data", "");
            return map0;
        }

        int num=questionnaireService.countQuestionnaire(publisherId);
       //  System.out.println("num的数量："+num);

        GetLimitNum G=new GetLimitNum();
        num=G.getLimitNum(num, pageSize);

      //   System.out.println("num的数量+："+num);
        int page=(startrow-1)*pageSize;//从哪一条开始
      //   System.out.println("page的值："+page);

        Questionnaire questionnaire=new Questionnaire(publisherId,page,pageSize);

        List<Questionnaire> questionnaires=questionnaireService.selectMyQuestionnaire(questionnaire);

        if (questionnaires.size()>0){
          //  System.out.println(questionnaires.size());
            for (int i=0;i<questionnaires.size();i++){
                Map<String,Object> map = new HashMap<String,Object>();
                map.put("questionnaireId",questionnaires.get(i).getQuestionnaireid());//问卷id
                map.put("questionnaireTitle",questionnaires.get(i).getQuestionnairetitle());//问卷标题
                map.put("releaseTime",questionnaires.get(i).getReleasetime());//发布时间
                String questionnaireExplain=questionnaires.get(i).getQuestionnaireexplain();//问卷说明 说明为“就业”的问卷在统计表中没有

                //通过问卷id查出问卷统计结果
               // System.out.println("问卷id"+questionnaires.get(i).getQuestionnaireid());

                QuestionnaireStatistical questionnaireStatistical= questionnaireService.selectStatistical(questionnaires.get(i).getQuestionnaireid());
                if (questionnaireStatistical==null||questionnaireStatistical.equals("")){
                    map.put("chooseNumber",0);//已填写人数
                    map.put("notChooseNumber",0);//未填写人数
                    mapList.add(map);
                }else {
                    //System.out.println(questionnaireStatistical.getChoosenumber());
                    map.put("chooseNumber",questionnaireStatistical.getChoosenumber());//已填写人数
                    map.put("notChooseNumber",questionnaireStatistical.getNotchoosenumber());//未填写人数
                    mapList.add(map);
                }

            }
            map0.put("pages",num);
            map0.put("list",mapList);
            map1.put("code",200);
            map1.put("message","查询成功");
            map1.put("data",map0);
        }else{
            map1.put("code",202);
            map1.put("message","查询无数据");
//            map1.put("data","");
        }



        return map1;
    }

    /**
     * 查询答题记录
     * @param request
     * @return
     */
    @RequestMapping(value = "selectQuestionnaireSubmit")
    public synchronized @ResponseBody Map<String,Object> selectQuestionnaireSubmit(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<String, Object>();
        String respondentId=request.getParameter("respondentId");//答题者id
        int questionnaireId=Integer.parseInt(request.getParameter("questionnaireId"));//问卷id

        List<QuestionnaireSubmit> list=questionnaireService.selectQuestionnaireSubmit(respondentId);

        if (list.size()>0){

            for (int i=0;i<list.size();i++){
                if (list.get(i).getQuestionnaireid()==questionnaireId){
                    //System.out.println("答过这张问卷");
                    map.put("code",200);
                    map.put("message","这张问卷已答过");
                    map.put("data",list.get(i));
                }else {
                    map.put("code",201);
                    map.put("message","这张问卷您没有回答");
//                    map.put("data","");
                }

            }

        }else {
         //System.out.println("没有回答过任何问卷");
            map.put("code",201);
            map.put("message","这张问卷您没有回答");
//            map.put("data","");
        }

        return map;
    }


    /**
     * 填写提交问卷  问卷类型不为scl-90与就业问卷的问卷
     * @param request
     * @return
     */
    @RequestMapping(value = "insertQuestionnaireSubmit")
    public synchronized @ResponseBody Map<String,Object> insertQuestionnaireSubmit(HttpServletRequest request) throws Exception{
        Map<String, Object> map = new HashMap<String, Object>();
        Map<String, Integer> map1 = new HashMap<String, Integer>();

        String questionnaireSubmits=request.getParameter("questionnaireSubmit");

        String studentId=request.getParameter("studentId");//答题者id
        String token=request.getParameter("token");

        StudentApp studentApp;
        studentApp = (StudentApp) tokenController.token1(studentId, token);
        if (studentApp==null){
            map.put("code", 206);
            map.put("message", "您暂无权限做此操作");
//            map.put("data", "");
            return map;
        }
        Student student=studentService.selectByKey(studentId);//查出学生信息

        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//可以方便地修改日期格式
        String nowTime = dateFormat.format( now );//时间

        long weekNum=0;
        int dayForWeek1 = 0;

        //这里需要计算获取  ！！！查出第几周，周几！
        TermBeginsTime termBeginsTime=evaluateTeacherService.selectTermBeginsTime();//查出开学时间

        if (termBeginsTime!=null){
            String termTime=termBeginsTime.getTermbeginstime();

            SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");

            Date a1 = format .parse(nowTime);
//            System.out.println("a1:"+a1);
            Date b1 = format .parse(termTime);
//            System.out.println("b1:"+b1);
//获取相减后周数
            weekNum = (a1.getTime()-b1.getTime())/(7*24*60*60*1000)+1;
            Calendar c1 = Calendar.getInstance();
            Calendar c2 = Calendar.getInstance();
            c1.setTime(format.parse(nowTime));
            c2.setTime(format.parse(termTime));
            if(c1.get(Calendar.DAY_OF_WEEK) == 1){
                dayForWeek1 = 7;
            }else if (c1.get(Calendar.DAY_OF_WEEK) == 2){
                dayForWeek1 = 1;
            }else if (c1.get(Calendar.DAY_OF_WEEK) == 3){
                dayForWeek1 = 2;
            }else if (c1.get(Calendar.DAY_OF_WEEK) == 4){
                dayForWeek1 = 3;
            }else if (c1.get(Calendar.DAY_OF_WEEK) == 5){
                dayForWeek1 = 4;
            }else if (c1.get(Calendar.DAY_OF_WEEK) == 6){
                dayForWeek1 = 5;
            }else if (c1.get(Calendar.DAY_OF_WEEK) == 7){
                dayForWeek1 = 6;
            }

            int dayForWeek2 = 0;
            if(c2.get(Calendar.DAY_OF_WEEK) == 1){
                dayForWeek2 = 7;
            }else{
                dayForWeek2 = c2.get(Calendar.DAY_OF_WEEK) - 1;
            }
            if (dayForWeek1<dayForWeek2){
                weekNum=weekNum+1;
            }
        }

        JSONObject jsonObject=JSONObject.fromObject(questionnaireSubmits);

        int questionnaireId=Integer.parseInt(jsonObject.getString("questionnaireId"));//问卷id
        String respondentId=jsonObject.getString("respondentId");//答题者id
        String answerResults =jsonObject.getString("answerResults");//答题的具体内容  是一个jsonArray


        JSONArray jsonArray=JSONArray.fromObject(answerResults);

        List<LabelThreeIndex> labelThreeIndexList=new ArrayList<LabelThreeIndex>();
        List<String> l=new ArrayList<String>();
       // String stuOptions="";
        String option="";
        String Score="";
        QuestionnaireResult questionnaireResult=new QuestionnaireResult();
        for (int i=0;i<jsonArray.size();i++){

            JSONObject jsonarray=jsonArray.getJSONObject(i);

            int questionNumber=Integer.parseInt(jsonarray.getString("questionNumber"));//问题id
            String stuOption=jsonarray.getString("stuOption");//答题者所选的选项，格式为：选择题："stuOption":4。。打分题："stuOption":1！5_2！4。。

            //System.out.println(questionNumber+"-------"+stuOption);
            QuestionnaireResult questionnaireResult1=new QuestionnaireResult();
            questionnaireResult1.setQuestionnaireid(questionnaireId);
            questionnaireResult1.setQuestionnumber(questionNumber);

            questionnaireResult=questionnaireService.selectByQuestionNum(questionnaireResult1);//通过问卷id和问题序号查出该问题信息


            if (questionnaireResult!=null){
                //关联的标签
                //格式：选择题：标签库名！三级指标名    打分题：选项1！标签库名！三级指标名！！选项2！标签库名！三级指标名。。
                String couplingIndex=questionnaireResult.getCouplingindex();

                    if (questionnaireResult.getProblemtypes().equals("选择题")){//问题类型为选择题
                        if (couplingIndex!=null&&!couplingIndex.equals("")) {//有关联的标签
                            LabelThreeIndex labelThreeIndex=new LabelThreeIndex();
                            String[] indexs=couplingIndex.split("!");
                            String packageName=indexs[0];
                            String threeIndex=indexs[1];
                            labelThreeIndex.setPackagelabel(packageName);
                            labelThreeIndex.setThreeindexname(threeIndex);

                            LabelThreeIndex labelThreeIndex1=evaluateTeacherService.selectByThreeIndexName(labelThreeIndex);

                            Float f=labelThreeIndex1.getProportion()*Float.parseFloat(stuOption);
                            labelThreeIndex1.setThreeIndexScore(f);

                            labelThreeIndexList.add(labelThreeIndex1);
                        }

                        option=questionNumber+"!"+stuOption;
                        //System.out.println("选择选项："+option);
                        map1.put(option,1);
                    }else if (questionnaireResult.getProblemtypes().equals("打分题")){//问题类型为打分题

                        String[] options=stuOption.split("_");
                        if (couplingIndex!=null&&!couplingIndex.equals("")){//有关联的标签

                            Map<Object,Object> m1=new HashMap<Object, Object>();
                            Map<Object,Object> m2=new HashMap<Object, Object>();
                            String[] couplingIndexs=couplingIndex.split("!!");
                            for (int y=0;y<couplingIndexs.length;y++){
                                String[] index=couplingIndexs[y].split("!");
                                String opt=index[0];
                                String packageName=index[1];
                                String threeIndex=index[2];
                                m1.put(opt,packageName+"!"+threeIndex);
                            }

                            for (int a=0;a<options.length;a++){
                                String[] scores=options[a].split("!");
                                String opt=scores[0];
                                String score=scores[1];
                                m2.put(opt,score);

                                option=questionNumber+"!"+options[a];
                                map1.put(option,1);
                            }

                            Set<Object> set =m1.keySet();
                            Iterator<Object> it = set.iterator();
                            while(it.hasNext()){
                                Object key = it.next();
                                if(m2.containsKey(key)){

                                    m2.put(key,m1.get(key)+"!"+m2.get(key));
                                }
                            }
                            String packageName="";
                            String threeIndex="";
                            Float score=0f;
                            LabelThreeIndex labelThreeIndex=new LabelThreeIndex();
                            for (Object key:m2.keySet()){
                                String[] indexsc=((String)m2.get(key)).split("!");
                                packageName=indexsc[0];
                                threeIndex=indexsc[1];
                                score=Float.parseFloat(indexsc[2]);

                                labelThreeIndex.setPackagelabel(packageName);
                                labelThreeIndex.setThreeindexname(threeIndex);


                                LabelThreeIndex labelThreeIndex1=evaluateTeacherService.selectByThreeIndexName(labelThreeIndex);

                                Float f=labelThreeIndex1.getProportion()*score;
                                labelThreeIndex1.setThreeIndexScore(f);
                                labelThreeIndexList.add(labelThreeIndex1);//
                            }

                        }
                        for (int a=0;a<options.length;a++){
                            option=questionNumber+"!"+options[a];
                            map1.put(option,1);
                        }
                    }

            }else {
                map.put("code",201);
                map.put("message","提取问题失败");
//                map.put("data","");
                return map;
            }
        }

        for (String key:map1.keySet()){
            l.add(key);
        }

        String stuO="";
        //System.out.println("l的长度："+l.size());
        for (int n=0;n<l.size()-1;n++){
            stuO=stuO+l.get(n)+"!!";
        }
        option=stuO+l.get(l.size()-1);
        //System.out.println("具体提交的选项"+option);


        List<LabelTwoIndex> labelTwoIndexes = new ArrayList<LabelTwoIndex>();
        if (labelThreeIndexList.size()>0){
            // //循环比较二级指标下的标签,算出第二级指标的得分

            for (int n = 0; n < labelThreeIndexList.size(); n++) {
                List<Float> score = new ArrayList<Float>();
                for (int m = labelThreeIndexList.size() - 1; m > n; m--) {
                    if (labelThreeIndexList.get(n).getIndexname().equals(labelThreeIndexList.get(m).getIndexname()) &&
                            labelThreeIndexList.get(n).getTwoindexname().equals(labelThreeIndexList.get(m).getTwoindexname())) {
                        score.add(labelThreeIndexList.get(m).getThreeIndexScore());
                        labelThreeIndexList.remove(m);
                    }
                }
                score.add(labelThreeIndexList.get(n).getThreeIndexScore());
                Float sum = 0f;
                for (Float s : score) {
                    sum += s;
                }
                //System.out.println(labelThreeIndexList.get(n).getTwoindexname() + "-的和：" + sum);

                LabelTwoIndex twoIndex=new LabelTwoIndex();
                twoIndex.setTwoindexname(labelThreeIndexList.get(n).getTwoindexname());
                twoIndex.setPackagelabel(labelThreeIndexList.get(n).getPackagelabel());


                LabelTwoIndex labelTwoIndex = evaluateTeacherService.selectByTwoIndexName(twoIndex);
                if (labelTwoIndex != null) {
                    Float twoIndexScore = sum * labelTwoIndex.getProportion();
                    LabelTwoIndex labelTwoIndex1 = new LabelTwoIndex();
                    labelTwoIndex1.setIndexname(labelTwoIndex.getIndexname());
                    labelTwoIndex1.setTwoindexname(labelTwoIndex.getTwoindexname());
                    labelTwoIndex1.setPackagelabel(labelTwoIndex.getPackagelabel());
                    labelTwoIndex1.setTwoindexscore(twoIndexScore);

                    labelTwoIndexes.add(labelTwoIndex1);//存入一个list labelTwoIndexes，里面全部为不同二级指标的得分
                } else {
                    map.put("code", 202);
                    map.put("message", "查询二级指标失败");
//                    map.put("data", "");
                    return map;
                }
            }

        }
        String indexScore = "";
        if (labelTwoIndexes.size()>0){

            //计算一级指标得分


            List<LabelIndex> labelIndexes = new ArrayList<LabelIndex>();
            for (int n = 0; n < labelTwoIndexes.size(); n++) {
                List<Float> score = new ArrayList<Float>();
                for (int m = labelTwoIndexes.size() - 1; m > n; m--) {
                    if (labelTwoIndexes.get(n).getIndexname().equals(labelTwoIndexes.get(m).getIndexname())) {
                        score.add(labelTwoIndexes.get(m).getTwoindexscore());
                        labelTwoIndexes.remove(m);

                    }
                }
                score.add(labelTwoIndexes.get(n).getTwoindexscore());
                Float sum = 0f;
                Float sum1 = 0f;
                for (Float s : score) {
                    sum += s;
                    sum1 = (float) (Math.round(sum * 100)) / 100;
                }
                //System.out.println(labelTwoIndexes.get(n).getIndexname() + "-的和：" + sum1);//还未乘以权重的值

                LabelIndex index=new LabelIndex();
                index.setIndexname(labelTwoIndexes.get(n).getIndexname());
                index.setPackagelabel(labelTwoIndexes.get(n).getPackagelabel());

                LabelIndex labelIndex = evaluateTeacherService.selectIndex(index);

                if (labelIndex != null) {
                    Float IndexScore = sum * labelIndex.getProportion();
                    LabelIndex labelIndex1 = new LabelIndex();  //乘以权重后的值
                    labelIndex1.setIndexname(labelIndex.getIndexname());
                    labelIndex1.setProportion(labelIndex.getProportion());
                    labelIndex1.setPackagelabel(labelIndex.getPackagelabel());
                    //labelIndex1.setIndexname(labelIndex.getIndexname());
                    labelIndex1.setIndexscore(IndexScore);

                    labelIndexes.add(labelIndex1);//存入一个list labelTwoIndexes，里面全部为不同二级指标的得分
                } else {
                    map.put("code", 203);
                    map.put("message", "查询一级指标失败");
//                    map.put("data", "");
                    return map;
                }

                if (indexScore == "") {
                    indexScore =labelTwoIndexes.get(n).getPackagelabel() + "!" + labelTwoIndexes.get(n).getIndexname() + "!" + sum1;
                } else {
                    indexScore = indexScore + "," + labelTwoIndexes.get(n).getPackagelabel() + "!" + labelTwoIndexes.get(n).getIndexname() + "!" + sum1;
                }

                // map1.put(labelTwoIndexes.get(l).getIndexname(), sum1);
                //System.out.println("指标得分" + indexScore);
            }

        }



//        Date now = new Date();
//        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//可以方便地修改日期格式
        String fillTime = dateFormat.format(now);//时间

//            QuestionnaireSubmit questionnaireSubmit=new QuestionnaireSubmit(questionnaireId,respondentId,option,indexScore,fillTime);
        QuestionnaireSubmit questionnaireSubmit=new QuestionnaireSubmit();
        questionnaireSubmit.setQuestionnaireid(questionnaireId);
        questionnaireSubmit.setRespondentid(respondentId);
        questionnaireSubmit.setStuoption(option);
        questionnaireSubmit.setIndexscore(indexScore);
        questionnaireSubmit.setFilltime(fillTime);
        questionnaireSubmit.setStudentname(student.getStudentname());
        questionnaireSubmit.setStudentschool(student.getStudentschool());
        questionnaireSubmit.setStudentcollege(student.getStudentcollege());
        questionnaireSubmit.setStudentmajor(student.getStudentmajor());
        questionnaireSubmit.setStudentgrade(student.getStudentclasss());
        questionnaireSubmit.setWeeknum((int)weekNum);

            int a=questionnaireService.insertQuestionnaireSubmit(questionnaireSubmit);

            if (a>0){

                Questionnaire questionnaire=questionnaireService.selectByQuestionnaireId(questionnaireId);//通过问卷id查出该问卷的面向人群

                if (questionnaire.getPublishobjects().equals("班级")||questionnaire.getPublishobjects().equals("课程")){
                    //如果问卷面向的是班级或课程，则为学生日志（暂时只有班级和课程）
                    //添加日志！！
                    //操作内容
                    String logContent="填写问卷“"+questionnaire.getQuestionnairetitle()+"”成功";
                    //System.out.println(logContent);
                    logController.logStudent(logContent, respondentId);

                }else {
                    //可扩展！！！！面向老师或后台...
                }

                QuestionnaireStudent questionnaireStudent=new QuestionnaireStudent();

                questionnaireStudent.setStudentid(respondentId);
                questionnaireStudent.setQuestionnaireid(questionnaireId);
                questionnaireStudent.setState("YES");

                int x=studentService.updateState(questionnaireStudent);
                if (x>0){
                    //状态修改成功
                }else {
                    map.put("code",205);
                    map.put("message","修改学生问卷关联状态失败");
//                    map.put("data","");
                    return map;
                }

                StudentCount studentCount = studentCountService.selectByPrimaryKey(studentId);
                StudentCount studentCount1 = new StudentCount();
                if (studentCount != null) {
                    studentCount1.setAnswerquestionnairenum(studentCount.getAnswerquestionnairenum() + 1);
                    studentCount1.setStudentid(studentId);
                    studentCountController.add(studentCount1, 1);
                } else {
                    studentCount1.setAnswerquestionnairenum(1);
                    studentCount1.setStudentid(studentId);
                    studentCountController.add(studentCount1, 0);
                }

                map.put("code",200);
                map.put("message","填写问卷成功");
                map.put("data","");
            }else {
                map.put("code",400);
                map.put("message","填写问卷失败");
//                map.put("data","");
                return map;
        }

        //通过问卷id查出统计表中信息
        QuestionnaireStatistical questionnaireStatistical=questionnaireService.selectStatistical(questionnaireId);

        if (questionnaireStatistical!=null){

            //统计详情，每道题每个选项选择的人数，
            // 格式：选择题：问题id！选项_选择人数。打分题：问题id！下级的小题！选的分数_选择人数
            //“问题1！选项1_选择人数！！问题1！选项2_选择人数！！问题2！选项1！分数1_选择人数！！问题2！选项1！分数2_选择人数...”
            //两个选项之间用双感叹号分割，都是英文状态下的符号
            String detailedStatistical=questionnaireStatistical.getDetailedstatistical();
            String detailedStatistical1="";
            Map<String,Object> m3=new HashMap<String,Object>();
            Map<String,Object> m4=new HashMap<String,Object>();
            List<String> list1=new ArrayList<String>();
            String strings=questionnaireStatistical.getIndexscore();//统计表中查出来的
            if (detailedStatistical==null||detailedStatistical.equals("")){

                String numberOption;
                String ds1="";
                List<String> list=new ArrayList<String>();
                for (String key:map1.keySet()){
                    numberOption=key+"_"+map1.get(key);
                    list.add(numberOption);
                }
                //System.out.println("list的长度！！！："+list.size());

                for (int i=0;i<list.size()-1;i++){

                    ds1=ds1+list.get(i)+"!!";
                }
                detailedStatistical1=ds1+list.get(list.size()-1);
                //System.out.println("具体选择：" + detailedStatistical1);

                //统计出来的一级指标总得分与选择的总人数，格式：标签库名！一级指标1_总得分_总人数，标签库名！一级指标2_总得分_总人数
                //多个一级指标用逗号分割

                //System.out.println("关联的标签？？？"+questionnaireResult.getCouplingindex());
                if (questionnaireResult.getCouplingindex()!=null&&!questionnaireResult.getCouplingindex().equals("")) {

                    //System.out.println("进行判断！");
                    if (strings != null && !strings.equals("")) {
                        //System.out.println("判断有值！！" + strings);
                        String[] strings1 = strings.split(",");
                        for (int x = 0; x < strings1.length; x++) {
                            String[] sco = strings1[x].split("_");
                            //System.out.println("sco的长度：" + sco.length);
                            String indexN = sco[0];
                            Float totalPoints = Float.parseFloat(sco[1]);
                            int headcount = Integer.parseInt(sco[2]);
                            m3.put(indexN, totalPoints + "_" + headcount);
                        }

                        String[] strings2 = indexScore.split(",");//添加的分数
                        for (int y = 0; y < strings2.length; y++) {
                            String[] sco = strings2[y].split("!");
                            String pack = sco[0];
                            String inde = sco[1];
                            Float scor = Float.parseFloat(sco[2]);
                            m4.put(pack + "!" + inde, scor);
                        }
                        Set<String> set = m4.keySet();
                        Iterator<String> it = set.iterator();
                        while (it.hasNext()) {
                            String key = it.next();
                            if (m3.containsKey(key)) {

                                String[] f = m3.get(key).toString().split("_");
                                Float totalPoints = Float.parseFloat(f[0]) + Float.parseFloat(m4.get(key).toString());
                                int headcount = Integer.parseInt(f[1]) + 1;

                                //System.out.println("key:" + key + "===总分：" + totalPoints + "====总人数：" + headcount);

                                m3.put(key, totalPoints + "_" + headcount);
                            } else {
                                m3.put(key, m3.get(key) + "_" + 1);
                            }

                        }
                    } else {

                        //System.out.println("进入else");
                        String[] strings2 = indexScore.split(",");//添加的分数
                        for (int y = 0; y < strings2.length; y++) {
                            String[] sco = strings2[y].split("!");
                            String pack = sco[0];
                            String inde = sco[1];
                            Float scor = Float.parseFloat(sco[2]);
//                        m3.put(pack+"!"+inde,scor);
                            String indexN = pack + "!" + inde;
                            m3.put(indexN, scor + "_" + 1);
                        }
                    }

                    for (Object key : m3.keySet()) {
                        String s = key + "_" + m3.get(key);
                        list1.add(s);
                    }


                    for (int z = 0; z < list1.size(); z++) {
                        if (Score == "") {
                            Score = list1.get(z);
                        } else {
                            Score = Score + "," + list1.get(z);
                        }
                    }

                    //System.out.println(Score);
                }else {
                    //没有关联标签
                    //System.out.println("没有关联标签");
                }
            }else{
                String[] ds=detailedStatistical.split("!!");//通过双感叹号分割，得出每个选项 格式：“问题1！选项1_选择人数”，“问题1！选项2_选择人数”。。

                Map<String, Integer> map2 = new HashMap<String, Integer>();

                for (int i=0;i<ds.length;i++){
                    String[] numberOptions=ds[i].split("_");
                    int num=Integer.parseInt(numberOptions[1]);
                    map2.put(numberOptions[0],num);
                }

                Set<String> set =map1.keySet();
                Iterator<String> it = set.iterator();
                while(it.hasNext()){
                    String key = it.next();
                    if(map2.containsKey(key)){

                        map2.put(key,map1.get(key)+map2.get(key));
                    }else {
                        map2.put(key,map1.get(key));
                    }
                }
                String numberOptions="";
                List<String> list=new ArrayList<String>();
                for (String key : map2.keySet()) {
                     numberOptions= key + "_" + map2.get(key);
                    list.add(numberOptions);
                }

//               System.out.println("list的长度1："+list.size());
                String ds1="";

                for (int j=0;j<list.size()-1;j++){

                    ds1=ds1+list.get(j)+"!!";
                }
                detailedStatistical1=ds1+list.get(list.size()-1);
               // System.out.println("具体选择："+detailedStatistical1);

                if (questionnaireResult.getCouplingindex()!=null&&!questionnaireResult.getCouplingindex().equals("")) {

                    String[] strings1 = strings.split(",");
                    for (int x = 0; x < strings1.length; x++) {
                        String[] sco = strings1[x].split("_");
//                    System.out.println("sco的长度："+sco.length);
                        String indexN = sco[0];
                        Float totalPoints = Float.parseFloat(sco[1]);
                        int headcount = Integer.parseInt(sco[2]);
                        m3.put(indexN, totalPoints + "_" + headcount);
                    }

                    String[] strings2 = indexScore.split(",");//添加的分数
                    //System.out.println(indexScore);
//                System.out.println("strings的长度："+strings2.length);
                    for (int y = 0; y < strings2.length; y++) {
//                    System.out.println("进入string2的循环。。");
                        String[] sco = strings2[y].split("!");
                        String pack = sco[0];
                        String inde = sco[1];
                        Float scor = Float.parseFloat(sco[2]);
//                        m3.put(pack+"!"+inde,scor);
                        String indexN = pack + "!" + inde;
                        m4.put(indexN, scor);
                    }

//                System.out.println("m4是否有值："+m4.size());

//                for (Object k:m3.keySet()){
////                    System.out.println("m3的key："+k+"==值"+m3.get(k));
//                }

                    Set<String> set1 = m4.keySet();
                    Iterator<String> it1 = set1.iterator();
                    while (it1.hasNext()) {

                        String key = it1.next();
//                    System.out.println("m4的key："+key+"==值："+m4.get(key));
                        if (m3.containsKey(key)) {

//                        System.out.println("判断包含！");
                            String[] f = m3.get(key).toString().split("_");
                            //System.out.println(m4.get(key));
                            Float totalPoints = Float.parseFloat(f[0]) + Float.parseFloat(m4.get(key).toString());
                            int headcount = Integer.parseInt(f[1]) + 1;

//                        System.out.println("key:"+key+"===总分："+totalPoints+"====总人数："+headcount);

                            m3.put(key, totalPoints + "_" + headcount);
                        } else {
//                        System.out.println("判断不包含！");
                            m3.put(key, m3.get(key) + "_" + 1);
                        }

                    }

//                System.out.println("m3的长度："+m3.size());

                    for (Object key : m3.keySet()) {
                        String s = key + "_" + m3.get(key);
                        list1.add(s);
                    }

//                System.out.println("list1的长度："+list1.size());
                    for (int z = 0; z < list1.size(); z++) {
                        if (Score == "") {
                            Score = list1.get(z);
                        } else {
                            Score = Score + "," + list1.get(z);
                        }
                        //System.out.println(Score);
                    }
                }else {
                    //System.out.println("没有关联的标签");
                }

                }
                //修改统计数据
                QuestionnaireStatistical questionnaireStatistical1=new QuestionnaireStatistical();
                questionnaireStatistical1.setQuestionnaireid(questionnaireStatistical.getQuestionnaireid());
                questionnaireStatistical1.setPublishobjects(questionnaireStatistical.getPublishobjects());
                questionnaireStatistical1.setNumber(questionnaireStatistical.getNumber());
                questionnaireStatistical1.setNotchoosenumber(questionnaireStatistical.getNotchoosenumber()-1);
                questionnaireStatistical1.setChoosenumber(questionnaireStatistical.getChoosenumber()+1);
                questionnaireStatistical1.setDetailedstatistical(detailedStatistical1);
                questionnaireStatistical1.setIndexscore(Score);
                questionnaireStatistical1.setStatisticaltime(fillTime);

                int x=questionnaireService.updateStatistical(questionnaireStatistical1);
                if (x>0){
                    //统计数据成功

                }else{
                    map.put("code",204);
                    map.put("message","统计结果失败");
//                    map.put("data","");
                    return map;
                }

                }else{
                    map.put("code",204);
                    map.put("message","统计结果失败");
//                    map.put("data","");
                    return map;
        }
        return map;
    }
}